#!/usr/bin/env bash

# {{ ansible_managed }}

## Shell Opts ----------------------------------------------------------------
set -e

## Functions -----------------------------------------------------------------
function cleanup {
  echo "Running Cleanup."
  systemctl unset-environment _WSREP_NEW_CLUSTER || systemctl set-environment _WSREP_NEW_CLUSTER=''
  if [[ -f "/etc/my{{ server_port }}.cnf.d/99_bootstrap.cnf" ]]; then
    rm /etc/my{{ server_port }}.cnf.d/99_bootstrap.cnf
  fi
}

function wait_operational {
  WAITCMD="while ! mysql  --no-defaults --socket=/var/lib/mysql{{ server_port }}/mysql.sock --silent --skip-column-names -e 'SHOW STATUS LIKE \"wsrep_evs_state\"' | grep -wq \"OPERATIONAL\"; do sleep 5; done"
  if ! timeout 180 sh -c "${WAITCMD}"; then
    echo "Cluster failed to return an \"OPERATIONAL\" state"
    return 1
  else
    echo "Cluster is now OPERATIONAL"
    return 0
  fi
}

function bootstrap_opts {
  cat > /etc/my{{ server_port }}.cnf.d/99_bootstrap.cnf <<EOF
[mysqld]
wsrep_new_cluster
EOF
}

## Main ----------------------------------------------------------------------
trap cleanup EXIT INT TERM

EXIT_CODE=0
if ! systemctl status mariadb{{ server_port }} > /dev/null; then
  systemctl set-environment _WSREP_NEW_CLUSTER='--wsrep-new-cluster'
  #if grep -rniq -e suse -e opensuse /etc/os-release; then
  bootstrap_opts
  #fi
  if systemctl start mariadb{{ server_port }}; then
    EXIT_CODE=3
  else
    echo "Cluster bootstrap failed."
    systemctl status mariadb{{ server_port }}
    exit 99
  fi
fi

wait_operational

cat <<EOF
NOTICE: Exit code 0 and 3 are success.
        Exit 0 is no change, exit 3 is change.
        Current Exit Code "${EXIT_CODE}"
EOF

exit ${EXIT_CODE}
